package com.infoland.afanmall.model.order.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.infoland.afanmall.R;

import butterknife.ButterKnife;
import butterknife.Unbinder;
/**
 * 待收货
 */


import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ToastUtils;
import com.infoland.afanmall.base.util.CONST;
import com.infoland.afanmall.base.util.CacheKit;
import com.infoland.afanmall.base.util.LogKit;
import com.infoland.afanmall.base.util.ToolsKit;
import com.infoland.afanmall.base.util.UserKit;
import com.infoland.afanmall.base.util.okhttp.OkHttpKit;
import com.infoland.afanmall.model.order.activity.MyOrderActivity;
import com.infoland.afanmall.model.order.activity.OrderInfoActivity;
import com.infoland.afanmall.model.order.adapter.AllOrderAdapter;
import com.infoland.afanmall.model.order.entity.OrderSelectResponse;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.List;

import butterknife.BindView;

/**
 * 全部订单页
 */
public class DSHFragment extends Fragment {

    Unbinder unbinder;
    @BindView(R.id.order_my_go_you_xuan)
    LinearLayout order_my_go_you_xuan;
    @BindView(R.id.order_my_go_you_xuan_txtx1)
    TextView order_my_go_you_xuan_txtx1;
    @BindView(R.id.order_my_go_you_xuan_img)
    ImageView order_my_go_you_xuan_img;


    @BindView(R.id.no_order_view)
    LinearLayoutCompat no_order_view;
    @BindView(R.id.order_my_refresh_layout)
    SmartRefreshLayout smartRefreshLayout;
    @BindView(R.id.order_my_recy)
    RecyclerView orderMyRecy;
    AllOrderAdapter thisAdapter;
    private int pageNumber = 1;
    private int pageSize = CONST.DSH_FRAGMENT_PAGE_SIZE;
    private int type = 0;// 订单类型 全部 - 0，待付款 - 1，待发货 - 2，待收货 - 3，完成 - 4，有退款 - 5 待评价 - 6
    private boolean lastPage = false;
    private boolean firstPage = true;
    private int totalPage = 0;
    private boolean load = false;
    private boolean ref = false;
    private boolean init = false;
    private boolean delete = false;
    private int postion = 0;
    int activityCode = 56;

    /*** 初始化分页参数**/
    private void initPageInfo() {
        init = true;
        load = false;
        ref = false;
        delete = false;
        pageNumber = 1;
        pageSize = CONST.DSH_FRAGMENT_PAGE_SIZE;
        lastPage = false;
        firstPage = true;
    }

    /*** main方法**/
    public void initData() {
        initPageInfo();
        getDSHOrder();
        order_my_go_you_xuan.setOnClickListener(v -> {
            MyOrderActivity myOrderActivity = (MyOrderActivity) getActivity();
            ToolsKit.returnResultYouXuan(myOrderActivity, null, CONST.RESULT_ORDER_TO_YOU_XUAN);
            getActivity().finish();
        });
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            load = true;
            ref = false;
            init = false;
            delete = false;
            startPage();
        });
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            ref = true;
            load = false;
            init = false;
            delete = false;
            pageNumber = 1;
            pageSize = 10;
            lastPage = false;
            firstPage = true;
            getDSHOrder();
        });
    }

    /*** 查询代收获状态的订单**/
    private void getDSHOrder() {
        startLoading();
        JSONObject para = getPagePara();
        para.put("type", 3);

        JSONObject params = new JSONObject();
        params.put("pageNumber", 1);
        params.put("pageSize", 10);
        new OkHttpKit().send(
                response200 -> {
                    OrderSelectResponse orderSelectResponse = JSONObject.parseObject(response200, OrderSelectResponse.class);
                    stopLoading();
                    setPageInfo(orderSelectResponse);
                    if (load) {
                        loadData(orderSelectResponse.getList());
                    } else if (ref) {
                        refData(orderSelectResponse.getList());
                    } else if (init) {
                        initAdapterData(orderSelectResponse.getList());
                    } else if (delete) {
                        /*** 预留**/
                    } else {
                        refData(orderSelectResponse.getList());
                    }
                },
                error401 -> {
                    smartRefreshLayout.finishLoadMore();
                    smartRefreshLayout.finishRefresh();
                    no_order_view.setVisibility(View.VISIBLE);

                },
                error -> {
                    smartRefreshLayout.finishLoadMore();
                    smartRefreshLayout.finishRefresh();
                    no_order_view.setVisibility(View.VISIBLE);
                }
        ).post(CONST.ORDER_LIST + UserKit.getAccessToken(), para, getActivity());
    }

    /*** 检查当前分页,然后开始查询**/
    private void startPage() {
        if (lastPage) {
            smartRefreshLayout.finishLoadMore();
            ToastUtils.showShort("已经是最后一页了");
        } else {
            pageNumber += 1;
            getDSHOrder();
        }
    }

    /*** 初始化适配器**/
    private void initAdapterData(List<OrderSelectResponse.ListBean> list) {
        isShowNoOrder(list);
        LogKit.E(" initAdapterData  ", "初始化适配器  ");
        thisAdapter = new AllOrderAdapter(R.layout.order_my_item, list, getActivity());
        thisAdapter.setOrderDeleteLinster((id, postion) -> {
            deleteOrderById(id, postion);
        });
        thisAdapter.setOrderInfoLinster(item -> {
            Bundle bundle = new Bundle();
            bundle.putInt("orderId", item.getOrder_id());
            bundle.putInt("orderItemId", item.getId());
            ToolsKit.go(OrderInfoActivity.class, bundle);
        });
        orderMyRecy.setLayoutManager(new LinearLayoutManager(CacheKit.APP_CONTEXT));
        orderMyRecy.setAdapter(thisAdapter);
    }

    /*** 是否展示没有订单界面**/
    private void isShowNoOrder(List<OrderSelectResponse.ListBean> list) {
        if (list.size() <= 0) {
            no_order_view.setVisibility(View.VISIBLE);
        } else {
            no_order_view.setVisibility(View.GONE);
        }
    }

    /*** 刷新数据**/
    private void refData(List<OrderSelectResponse.ListBean> list) {
        isShowNoOrder(list);
        thisAdapter.setNewData(list);
        thisAdapter.loadMoreComplete();
        smartRefreshLayout.finishRefresh();
        LogKit.E(" refData  ", "刷新数据  " + list.size());
    }

    /*** 加载数据**/
    private void loadData(List<OrderSelectResponse.ListBean> list) {
        isShowNoOrder(list);
        thisAdapter.addData(list);
        thisAdapter.loadMoreComplete();
        smartRefreshLayout.finishLoadMore();
        LogKit.E(" loadData  ", "加载数据  ");
    }


    /*** 设置分页参数（请求数据之后）**/
    private void setPageInfo(OrderSelectResponse orderSelectResponse) {
        LogKit.E(" setPageInfo  ", "设置分页参数  ");
        pageNumber = orderSelectResponse.getPageNumber();
        pageSize = orderSelectResponse.getPageSize();
        lastPage = orderSelectResponse.isLastPage();
        firstPage = orderSelectResponse.isFirstPage();
        totalPage = orderSelectResponse.getTotalPage();

    }

    /*** 获取分页参数**/
    private JSONObject getPagePara() {
        LogKit.E(" getPagePara  ", "获取分页参数  ");
        JSONObject para = new JSONObject();
        para.put("pageNumber", pageNumber); //页数
        para.put("pageSize", pageSize); //条数
        para.put("type", type);
        return para;
    }

    /*** 删除订单**/
    private void deleteOrderById(int id, int potion) {
        LogKit.E(" 删除订单  ", "  id  " + id);
        LogKit.E(" 删除订单  ", "  potion  " + potion);
        JSONObject para = new JSONObject();
        para.put("orderId", id);
        postion = potion;


        new OkHttpKit().send(
                response200 -> {
                    JSONObject jsonObject = JSONObject.parseObject(response200);
                    LogKit.E(" 删除订单  ", "  jsonObject  " + jsonObject);

//                thisAdapter.set
                    if (jsonObject.getBoolean("success")) {
                        List<OrderSelectResponse.ListBean> data = thisAdapter.getData();
                        data.remove(postion);
                        thisAdapter.setNewData(data);
                        thisAdapter.loadMoreComplete();
                        isShowNoOrder(data);
                    } else {
                        ToastUtils.showShort("删除失败");
                    }

                },
                error401 -> {
                    ToastUtils.showShort("删除失败");
                },
                error -> {
                    ToastUtils.showShort("删除失败");
                }
        ).post(CONST.ORDER_DELETE + UserKit.getAccessToken(), para, getActivity());
    }


    /*** 启动加载AV**/
    private void startLoading() {
        LogKit.E(" startLoading  ", "startLoading  ");
    }

    /*** 停止加载AV**/
    private void stopLoading() {
        LogKit.E(" stopLoading  ", "stopLoading  ");

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.order_my_recy, container, false);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        ToolsKit.deleteOKHttp(getActivity());
        super.onDestroy();
    }
}
